﻿using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class AppleCtrl : MonoBehaviour, IControl<AppleCtrl> {
	// === Unity ======================================================================================================
	private void Update() {
		if (!CheckForApples()) {
			GenerateFood();
		}
	}

	// === Public =====================================================================================================
	#region IControl
	public AppleCtrl GetControl() {
		return this;
	}

	public void Initialize() {
		FillListTypes();
		for (int i = 0; i < SettingsLevelModel.AppleCount; i++) {
			GenerateFood();
		}
	}

	public void Destroy() {
		Managers.Element.DestroyElements(Tools.Element.GetElements(FieldElementType.GreenApple));
		Managers.Element.DestroyElements(Tools.Element.GetElements(FieldElementType.RedApple));
		Destroy(gameObject);
	}
	#endregion

	// === Private ====================================================================================================
	private List<FieldElementType> _appleTypes;

	private void FillListTypes() {
		_appleTypes = new List<FieldElementType> {
			FieldElementType.GreenApple,
			FieldElementType.RedApple
		};
	}

	private void GenerateFood() {
		var pointX = (int)Random.Range(0, SettingsLevelModel.FieldSize.x);
		var pointY = (int)Random.Range(0, SettingsLevelModel.FieldSize.y);
		var pos = new Vector3(pointX, 0, pointY);
		if (CheckCollisionWithElement(pos) || CheckCollisionWithBody(pos)) {
			return;
		}
		var type = _appleTypes[Random.Range(0, _appleTypes.Count)];
		Managers.Element.CreateElement(type, pos);
	}

	private bool CheckCollisionWithElement(Vector3 point) {
		return GameData.GetInstance.Elements.Any(fieldElement => point.Equals(fieldElement.Position));
	}

	private bool CheckCollisionWithBody(Vector3 point) {
		return GameData.GetInstance.Bodies.Select(body => body.BodyData.CurPoint).Contains(point);
	}

	private bool CheckForApples() {
		var apples = new List<FieldElement>();
		apples.AddRange(Tools.Element.GetElements(FieldElementType.GreenApple));
		apples.AddRange(Tools.Element.GetElements(FieldElementType.RedApple));
		return SettingsLevelModel.AppleCount <= apples.Count;
	}
}